package com.ibeetl.cms.service;


import com.ibeetl.admin.core.service.CoreBaseService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.cms.dao.CmsCommentDao;
import com.ibeetl.cms.entity.CmsComment;
import com.ibeetl.cms.web.query.CmsCommentQuery;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;






/**
 * CmsComment Service
 */

@Service
@Transactional
public class CmsCommentService extends CoreBaseService<CmsComment>{

    @Autowired private CmsCommentDao cmsCommentDao;

    public PageQuery<CmsComment>queryByCondition(PageQuery query){
        PageQuery<CmsComment> ret =  cmsCommentDao.queryByCondition(query);
        for (Iterator<CmsComment> iterator = ret.getList().iterator(); iterator.hasNext(); ) {
            CmsComment next =  iterator.next();
            setChildComment(next);
        }
        queryListAfter(ret.getList());
        return ret;
    }

    /**
     * 此方法使用ArticleQuery作为参数，是因为使用PageQuery作为参数时无法用toString方法，导致无法使用缓存
     */
    @Cacheable(value = CorePlatformService.COMMENT_CACHE_LIST)
    public PageQuery<CmsComment>queryByCondition(CmsCommentQuery condition){
        PageQuery page = condition.getPageQuery();
        return this.queryByCondition(page);
    }

    @CacheEvict(cacheNames = {CorePlatformService.COMMENT_CACHE_LIST}, allEntries = true)
    public void clearCommentListCache() {
        //没有做任何事情，交给spring cache来处理了
    }

    public void setChildComment(CmsComment comment) {
        CmsCommentQuery condition = new CmsCommentQuery();
        condition.setParentId(comment.getId());
        PageQuery query = condition.getPageQuery();
        PageQuery<CmsComment> childRet =  cmsCommentDao.queryByCondition(query);
        if (childRet.getTotalRow() > 0) {
            comment.setChildList(childRet.getList());
        }
        for (Iterator<CmsComment> iterator = childRet.getList().iterator(); iterator.hasNext(); ) {
            CmsComment next =  iterator.next();
            this.setChildComment(next);
        }
    }

    public PageQuery<CmsComment>commentList(PageQuery query) {
        //TODO 准备写包含子评论的语句
        return null;
    }

    public void batchDelCmsComment(List<Integer> ids){
        try {
            cmsCommentDao.batchDelCmsCommentByIds(ids);
        } catch (Exception e) {
            throw new PlatformException("批量删除CmsComment失败", e);
        }
    }
}